package com.bulunsh.wensen.controller;

import com.bulunsh.wensen.model.AuthenticationRequest;
import com.bulunsh.wensen.model.UserDto;
import com.bulunsh.wensen.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class LoginController {

    @Autowired
    AuthenticationService authenticationService;

    @RequestMapping(value = "login",produces = "text/plain;charset=UTF-8")
    public String login(AuthenticationRequest authenticationRequest, HttpSession httpSession){

        UserDto userDto =authenticationService.Authentication(authenticationRequest);
        httpSession.setAttribute(UserDto.SESSION_USER_KEY,userDto);
        return userDto.getUsername()+"登录成功";

    }

    @RequestMapping(value = "/logout",produces = "text/plain;charset=UTF-8")
    public String logout(HttpSession httpSession){
        httpSession.invalidate();
        return "退出成功";
    }

    @RequestMapping(value = "/r/r1",produces = "text/plain;charset=UTF-8")
    public String r1(HttpSession httpSession){
        String name = "";
        Object o = httpSession.getAttribute(UserDto.SESSION_USER_KEY);
        if (o == null) {
            name = "匿名";
        }else {
            UserDto userDto = (UserDto)o;
            name = userDto.getUsername();
        }
        return name+"访问资源r1";
    }

    @RequestMapping(value = "/r/r2",produces = "text/plain;charset=UTF-8")
    public String r2(HttpSession httpSession){
        String name = "";
        Object o = httpSession.getAttribute(UserDto.SESSION_USER_KEY);
        if (o == null) {
            name = "匿名";
        }else {
            UserDto userDto = (UserDto)o;
            name = userDto.getUsername();
        }
        return name+"访问资源r2";
    }
}
